using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace Pixysoft
{
    //http://blog.csdn.net/yefanqiu/archive/2007/08/15/1744847.aspx
    public class ColorCoder
    {
        private static ColorCoder instance;
        public static ColorCoder Instance
        {
            get
            {
                lock (typeof(ColorCoder))
                {
                    if (instance == null)
                        instance = new ColorCoder();
                    return instance;
                }
            }
        }

        public Color HtmlToColor(string html)
        {
            //html = #123456

            if (!html.Contains("#"))
                return Color.Empty;

            if (html.Length != 7)
                return Color.Empty;

            int r = Convert.ToInt16("0x" + html.Substring(1, 2), 16);

            int g = Convert.ToInt16("0x" + html.Substring(3, 2), 16);

            int b = Convert.ToInt16("0x" + html.Substring(5, 2), 16);

            return Color.FromArgb(r, g, b);
        }

        public string ColorToHtml(Color color)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append("#");

            int colorvalue = 0;

            builder.Append(StringCoder.AddZero(Convert.ToString(color.R, 16), 2));

            colorvalue = (int)color.G;

            builder.Append(StringCoder.AddZero(Convert.ToString(color.G, 16), 2));

            colorvalue = (int)color.B;

            builder.Append(StringCoder.AddZero(Convert.ToString(color.B, 16), 2));

            return builder.ToString();
        }

        private void test()
        {
            string color = "#121212";

            Console.WriteLine(ColorToHtml(HtmlToColor(color)));
        }
    }
}
